package org.example;

import org.example.dao.Main;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.websocket.Session;
import org.example.dao.DBUtil;


@ServerEndpoint(value = "/websocket")
public class ChatEndpoint {
    Main main = new Main();
    private static final Set<Session> sessions = new CopyOnWriteArraySet<>();
    private static final int MERCHANT_USERNAME = 101;

    // 用于指示最后一条消息是否来自客服的标志
    private static boolean lastMessageFromMerchant = false;

    @OnOpen
    public void onOpen(Session session) {
        sessions.add(session);
        System.out.println("新连接: " + session.getId());
    }

    @OnMessage
    public void onMessage(String message, Session session) throws IOException, SQLException {
        if (containsImagePath(message)) {
            System.out.println(message);
            // 图片消息
            main.saveImageToDatabase(message);
        } else {
            System.out.println(message);
            // 文本消息
            main.chat(message);
        }
        broadcastMessage(message, session);

        if (containsMerchantUsername(message)) {
            System.out.println(containsMerchantUsername(message));
            lastMessageFromMerchant = true;
        } else {
            if (!lastMessageFromMerchant) {
                // 发送确认消息给客户端
                String confirmationMessage = createConfirmationMessage(session);
                session.getBasicRemote().sendText(confirmationMessage);
            }
        }
    }

    public boolean containsMerchantUsername(String message) {
        Pattern pattern = Pattern.compile("\"sender\":\"(.*?)\"");
        Matcher matcher = pattern.matcher(message);
        int sender = 0;
        if (matcher.find()) {
            String senderStr = matcher.group(1); // 提取匹配的字符串
            try {
                sender = Integer.parseInt(senderStr); // 将字符串转换为整数
            } catch (NumberFormatException e) {
                System.out.println("无法将匹配的字符串转换为整数。");
                e.printStackTrace();
            }
        }
        return sender == MERCHANT_USERNAME;
    }

    public boolean containsImagePath(String message) {
        return message.contains(".jpg") || message.contains(".jpeg") || message.contains(".png") || message.contains(".gif");
    }

    @OnClose
    public void onClose(Session session) {
        sessions.remove(session);
        System.out.println("连接关闭: " + session.getId());

        // 如果关闭的会话是客服的，重置标志
        if (isMerchantSession(session)) {
            lastMessageFromMerchant = false;
        }
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        System.err.println("WebSocket错误: " + throwable.getMessage() + " 来自: " + session.getId());
        // 处理错误
    }

    // 创建确认消息的方法
    private String createConfirmationMessage(Session session) {
        Integer sender = (Integer) session.getUserProperties().get("sender");
        return "{\"sender\":\"" + MERCHANT_USERNAME + "\",\"receiver\":\"" + sender + "\", \"message_content\":\"你的消息已收到\"}";
    }

    private void broadcastMessage(String message, Session currentSession) throws IOException {
        for (Session s : sessions) {
            if (s.isOpen() && !s.equals(currentSession)) {
                s.getBasicRemote().sendText(message);
                if(!lastMessageFromMerchant) {
                    List<Integer> loggedInUserIds = main.getLoggedInUserIds();
                    for (int userId : loggedInUserIds) {
                        main.updateLastRecordReceiver(userId);
                    }
                }
                main.updateLastRecordReceiverBasedOnPrevious();
                lastMessageFromMerchant = false;
            }
        }
    }

    private boolean isMerchantSession(Session session) {
        // 实现识别客服会话的逻辑
        // 可以基于会话的属性或某些标识符
        // 这里假设使用用户名作为标识符
        try {
            int sender = (int) session.getUserProperties().get("sender");
            return (MERCHANT_USERNAME==sender);
        } catch (Exception e) {
            return false;
        }
    }
}
